<?php
/**
 * Created by PhpStorm.
 * User: wuxiansheng
 * Date: 2018/8/14
 * Time: 20:44
 */

namespace App\Console\Service;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class RptileMessionService
{

    private $exchange = 'router'; // 交换器，在我理解，如果两个队列使用一个交换器就代表着两个队列是同步的，这个队列里存在的消息，在另一个队列里也会存在
    private $queue = 'test'; // 队列名称
    private $connection = [];

    public function __construct()
    {
        $this->connection = [
            "host" => '127.0.0.1',
            "port" => 5672,
            "user" => 'guest',
            "pass" => 'guest',
            "vhost" => '/'
        ];
    }

    public function download()
    {
        $exchange = $this->exchange;
        $queue = $this->queue;
        $c = $this->connection;
        $connection = new AMQPStreamConnection($c['host'], $c['port'] , $c['user'], $c['pass'], $c['vhost']); // 创建连接
        $channel = $connection->channel();
        $channel->queue_declare($queue, false, true, false, false);
        $channel->exchange_declare($exchange, 'direct', false, true, false);
        $channel->queue_bind($queue, $exchange); // 队列和交换器绑定
        $messageBody = 'testinfo12'; // 要推送的消息
        $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
        $channel->basic_publish($message, $exchange); // 推送消息
        $channel->close();
        $connection->close();
    }

    public function analyzer()
    {
        $queue = $this->queue;
        $c = $this->connection;
        $connection = new AMQPStreamConnection($c['host'], $c['port'] , $c['user'], $c['pass'], $c['vhost']); // 创建连接
        $channel = $connection->channel();
        $message = $channel->basic_get($queue); //取出消息
        print_r($message->body);
        $channel->basic_ack($message->delivery_info['delivery_tag']); // 确认取出消息后会发送一个ack来确认取出来了，然后会从rabbitmq中将这个消息移除，如果删掉这段代码，会发现rabbitmq中的消息还是没有减少
        $channel->close();
        $connection->close();
    }

}